from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_user, logout_user, current_user
# from ..app import db, login_manager  # 修改为绝对导入
from .app import db, login_manager
from .models import User  # 修改为绝对导入
from werkzeug.security import generate_password_hash, check_password_hash

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/')
def home():
    return redirect(url_for('auth.login'))

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(username=username).first()
        
        if user and check_password_hash(user.password, password):
            login_user(user)
            if user.role == '管理员':
                return redirect(url_for('admin.admin_dashboard'))
            else:
                return redirect(url_for('user.dashboard'))
        flash('用户名或密码错误', 'danger')
    return render_template('login.html')

@auth_bp.route('/register', methods=['POST'])
def register():
    try:
        username = request.form.get('username')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')
        role = request.form.get('role')
        admin_key = request.form.get('admin_key')
        if role not in ['查看员', '管理员']:
            flash('只能注册查看员或管理员身份', 'danger')
            return redirect(url_for('auth.login'))

        if not all([username, password, confirm_password]):
            flash('所有字段必须填写', 'danger')
            return redirect(url_for('auth.login'))

        if password != confirm_password:
            flash('两次输入的密码不一致', 'danger')
            return redirect(url_for('auth.login'))

        if User.query.filter_by(username=username).first():
            flash('用户名已存在', 'danger')
            return redirect(url_for('auth.login'))

        if role == '管理员':
            correct_admin_key = 'vp6n8uns18?'  
            if admin_key != correct_admin_key:
                flash('管理员密钥不正确', 'danger')
                return redirect(url_for('auth.login'))

        hashed_password = generate_password_hash(password)
        new_user = User(
            username=username,
            password=hashed_password,
            role=role
        )
        
        db.session.add(new_user)
        db.session.commit()
        flash('注册成功，请登录', 'success')
        return redirect(url_for('auth.login', registered='true'))

    except Exception as e:
        db.session.rollback()
        flash(f'注册失败: {str(e)}', 'danger')
        return redirect(url_for('auth.login'))

@auth_bp.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('auth.login'))